﻿using P2PWeb.Common;
using P2PWeb.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Objects.DataClasses;

namespace P2PWeb.Controllers
{
    public class UpLoadInfo
    {
        public string[] FileNames { get; set; }
        public int ID { get; set; }
    }

    public class BorrowInfo
    {
        public int Id { get; set; }

        public string Name { get; set; }


        [DisplayName("借款用途")]
        [Required(ErrorMessage = "请选择借款用途.")]
        [Range(1, 13, ErrorMessage = "请选择借款用途")]
        /// <summary>
        /// 用途
        /// </summary>
        public int Use { get; set; }

        [DisplayName("借款金额")]
        [Required(ErrorMessage = "请输入借款金额")]
        [Range(100, 10000000, ErrorMessage = "借款金额必须在100元到1000万之间")]
        [RegularExpression("^[0-9]*$", ErrorMessage = "借款金额必须为数字")]
        [MoneyRange]
        /// <summary>
        /// 借款金额
        /// </summary>
        public int BorrowMoney { get; set; }

        [Required(ErrorMessage = "请输入借款利息")]
        //[DataType( System.ComponentModel.DataAnnotations.DataType.Currency,ErrorMessage = "借款利息必须是数字")]
        //[RegularExpression("^[0-9]*$", ErrorMessage = "借款利息必须是数字")]
        [RegularExpression(@"^\d+(\.\d{1,2})?$",ErrorMessage = "借款利息必须是数字并且最多只能输入2位小数")]
        [Range(1, 30, ErrorMessage = "借款利息最少为1%,最高为30%")]
        public double InterestRate { get; set; }

        [DisplayName("投标结束时间")]
        [DateTimeGreaterDateTimeNow()]
        //[DateTimeRangeByStartTimeAndEndTime("StartTime", "EndTime")]
        [DataType(DataType.Date, ErrorMessage = "时间格式为 yyyy-mm-dd(yyyy为年份，mm为月份，dd为天数)")]

        //[Range(1,32,ErrorMessage="请选择借款期限")]
        /// <summary>
        /// 借款期限
        /// </summary>
        public DateTime? BorrowDeadline { get; set; }



        [DisplayName("开始时间")]
        [DateTimeGreaterDateTime("BorrowDeadline")]
        [Required(ErrorMessage = "请填写开始时间")]
        [DataType(DataType.Date, ErrorMessage = "时间格式为 yyyy-mm-dd(yyyy为年份，mm为月份，dd为天数)")]
        public DateTime? StartTime { get; set; }

        [DisplayName("结束时间")]
        [Required(ErrorMessage = "请填写结束时间")]
        [DateTimeGreaterDateTime("StartTime")]
        [DataType(DataType.Date, ErrorMessage = "时间格式为 yyyy-mm-dd(yyyy为年份，mm为月份，dd为天数)")]
        public DateTime? EndTime { get; set; }

        [Range(1, 9999, ErrorMessage = "请选择交易类型")]
        /// <summary>
        /// 交易类型
        /// </summary>
        public int CalcType { get; set; }

        [Required(ErrorMessage = "请输入借款描述")]
        /// <summary>
        /// 借款描述
        /// </summary>
        public string Remark { get; set; }

        [Range(1, 9999, ErrorMessage = "请选择抵押类型")]
        /// <summary>
        /// 抵押类型
        /// </summary>
        public MortgageAttachment MortgageAttachment { get; set; }

        //[Required(ErrorMessage="请输入您的qq号码")]
        ///// <summary>
        ///// qq号码
        ///// </summary>
        //public string QQNumber { get; set; }

        //[Required(ErrorMessage="请输入您的手机号码")]
        ///// <summary>
        ///// 手机号码
        ///// </summary>
        //public string Phone { get; set; }

        public static BorrowInfo Search(int id)
        {
            if (id == 1)
                return new BorrowInfo()
                {
                    Id = 1,
                    BorrowDeadline = null,
                    BorrowMoney = 100000,
                    //Phone = "13402038899",
                    //QQNumber = "78043912",
                    Remark = "用于装修",
                    Use = (int)BorrowUse.Invest,
                };
            else
                return new BorrowInfo() { Use = -1, CalcType = (int)Common.CalcType.LookThrough };
        }
    }


    public class BorrowUseInfo
    {
        public int Use { get; set; }

        public string DisplayName { get; set; }

        public static readonly BorrowUseInfo[] BorrowUses = new BorrowUseInfo[] 
        {
            new BorrowUseInfo(){ Use=(int)BorrowUse.none,DisplayName="请选择"},
            new BorrowUseInfo(){ Use=(int)BorrowUse.BuyHouse,DisplayName="购房"},
            new BorrowUseInfo(){ Use=(int)BorrowUse.BuyCar,DisplayName="购车"},
            new BorrowUseInfo(){ Use=(int)BorrowUse.Marry,DisplayName="结婚"},
            new BorrowUseInfo(){ Use=(int)BorrowUse.Business,DisplayName="创业"},
            new BorrowUseInfo(){ Use=(int)BorrowUse.EducationalTraining,DisplayName="教育培训"},
            new BorrowUseInfo(){ Use=(int)BorrowUse.PurchaseOfFurniture,DisplayName="家具"},
            new BorrowUseInfo(){ Use=(int)BorrowUse.Fitment,DisplayName="装修"},
            new BorrowUseInfo(){ Use=(int)BorrowUse.Trip,DisplayName="旅游"},
            new BorrowUseInfo(){ Use=(int)BorrowUse.Medical,DisplayName="医疗"},
            new BorrowUseInfo(){ Use=(int)BorrowUse.Spend,DisplayName="日常消费"},
            new BorrowUseInfo(){ Use=(int)BorrowUse.PaymentOfDebts,DisplayName="偿还债务"},
            new BorrowUseInfo(){ Use=(int)BorrowUse.Invest,DisplayName="投资"},
            new BorrowUseInfo(){ Use=(int)BorrowUse.Other,DisplayName="其它"},
        };
    }

     [AccountAuthorize(AccountType.Admin, AccountType.LookThrough, AccountType.User, AccountType.Agent)]
    public class BorrowStep1Controller : BaseController
    {
        //
        // GET: /BorrowStep1/
        [AcceptVerbs("GET")]
        public ActionResult Index()
        {
            using (var context = new Repository<P2PModelContainer>())
            {
                Account curAccount = context.GetEntityByID<Account>(CurrentUserInfo.ID);
                if (curAccount.Type == (int)AccountType.Agent)
                {
                    ViewData["type"] = true;
                }
                else
                {
                    ViewData["type"] = false;
                }

                if (curAccount.Status != (int)AccountState.Pass)
                {
                    switch (curAccount.Status)
                    {
                        case (int)AccountState.New:
                            return new ContentResult()
                            {
                                Content = "<script>alert('您还未通过实名认证,确定后填写实名信息');window.location='/account/AccountUploadify'</script>",
                            };
                        case (int)AccountState.LookThrough:
                            return new ContentResult()
                            {
                                Content = "<script>alert('审核中，请稍后');window.location='/account/'</script>",
                            };
                        case (int)AccountState.Unfit:
                            return new ContentResult()
                            {
                                Content = "<script>alert('实名认证失败,请重新审核');window.location='/account/AccountUploadify'</script>",
                            };
                        default:
                            break;
                    }
                }
            }
            BorrowInfo borrow = null;
            using (var context = new Repository<P2PModelContainer>())
            {
                borrow = new BorrowInfo()
                {
                    Use = -1,
                    BorrowMoney = 100,
                    CalcType = (int)Common.CalcType.LookThrough,
                    MortgageAttachment = Common.MortgageAttachment.House,
                    //Phone=account.Cellphone,
                };
            }
            return View(borrow);
        }

        [AcceptVerbs("Post")]
        [ValidateAntiForgeryToken]
        public ActionResult SaveAndNavToStep2(BorrowInfo borrowInfo)
        {
            using (var context = new Repository<P2PModelContainer>())
            {
                List<string> includes = new List<string>() { "AccountInfo", "AccountAuthentication" };
                Account curAccount = context.GetEntityByID<Account>(CurrentUserInfo.ID, includes);

                if (curAccount.Type == (int)AccountType.Agent)//判断是否为代理商
                {
                    if (curAccount.AgentID != null)
                    {
                        Campaign campaign = new Campaign()
                        {
                            Amount = borrowInfo.BorrowMoney,
                            DueDate = borrowInfo.BorrowDeadline,
                            Info = borrowInfo.Remark.ToString(),
                            CreationTime = DateTime.Now,
                            CreationUser = CurrentUserInfo.Name,
                            StartDate = borrowInfo.StartTime.Value,
                            EndDate = borrowInfo.EndTime.Value,//DateTime.Now.AddMonths(borrowInfo.BorrowDeadline),
                            Name = borrowInfo.Name,
                            Status = (int)CampaignState.Draft,
                            CalcType = borrowInfo.CalcType,
                            AccountID = curAccount.ID,
                            AgentID = curAccount.AgentID, //AgentId
                            InterestRate = borrowInfo.InterestRate / 100,
                            Mortgage = (int)borrowInfo.MortgageAttachment
                        };
                        campaign.CampUpLoad = new EntityCollection<CampUpLoad>();
                        var query = context.Add(campaign);
                        return RedirectToAction("NavToUploadifyMortgage", "borrowStep1", new { borrowId = query.ID });
                    }
                    else
                    {
                        return new ContentResult() { Content = "<script>alert('该用户不是代理商，不能发布代理商信息');window.location='/account/'</script>" };
                    }
                }
                else
                {
                    Campaign campaign = new Campaign()
                    {
                        Amount = borrowInfo.BorrowMoney,
                        DueDate = borrowInfo.BorrowDeadline,
                        Info = borrowInfo.Remark.ToString(),
                        CreationTime = DateTime.Now,
                        CreationUser = CurrentUserInfo.Name,
                        StartDate = borrowInfo.StartTime.Value,
                        EndDate = borrowInfo.EndTime.Value,//DateTime.Now.AddMonths(borrowInfo.BorrowDeadline),
                        Name = borrowInfo.Name,
                        Status = (int)CampaignState.Draft,
                        CalcType = borrowInfo.CalcType,
                        AccountID = curAccount.ID,
                        InterestRate = borrowInfo.InterestRate / 100,
                        Mortgage = (int)borrowInfo.MortgageAttachment
                    };
                    campaign.CampUpLoad = new EntityCollection<CampUpLoad>();
                    var query = context.Add(campaign);
                    return RedirectToAction("NavToUploadifyMortgage", "borrowStep1", new { borrowId = query.ID });
                }
            }
        }


        public static bool CheckMortgageAttachment(Campaign campaign, Account account, out ContentResult result)
        {
            result = null;
            if (campaign.Mortgage == (int)MortgageAttachment.House)
            {
                var checkHouseMoney = decimal.Parse(System.Configuration.ConfigurationManager.AppSettings["CheckHouseMoney"]);
                if (account.Money < checkHouseMoney)
                {
                    result = new ContentResult()
                    {
                        Content = string.Format("<script>alert('房产抵押审核需要{0}元人民币，您当前余额不足，请去充值');window.location='/chongzhi'</script>"
                        , checkHouseMoney.ToString("N2")),
                    };
                    return false;
                }
            }
            else
            {
                var checkCarMoney = decimal.Parse(System.Configuration.ConfigurationManager.AppSettings["CheckCarMoney"]);
                if (account.Money < checkCarMoney)
                {
                    result = new ContentResult()
                    {
                        Content = string.Format("<script>alert('汽车抵押审核需要{0}元人民币，您当前余额不足，请去充值');window.location='/chongzhi'</script>"
                        , checkCarMoney.ToString("N2")),
                    };
                    return false;
                }
            }
            return true;
        }

        private bool CheckCampaign(Campaign campaign, Account account, out ContentResult result)
        {
            result = null;
            if (campaign == null)
                throw new Exception("不存在改订单");
            if (campaign.Status != (int)CampaignState.Draft)
            {
                throw new Exception("非法操作");
            }
            if (campaign.AccountID != account.ID)
            {
                throw new Exception("非法操作");
            }
            if (!CheckMortgageAttachment(campaign,account, out result))
            {
                return false;
            }
            return true;
        }



        public ActionResult FinsishUploadifyMortgage(UpLoadInfo uploadInfo)
        {
            using (var context = new Repository<P2PModelContainer>())
            {
                Account curAccount = context.GetEntityByID<Account>(CurrentUserInfo.ID);
                Campaign campaign = context.GetEntityByID<Campaign>(uploadInfo.ID, new List<string>(new[] { "CampUpLoad" }));
                ContentResult result = null;
                if (!CheckCampaign(campaign, curAccount, out result))
                {
                    return result;
                }
                if (uploadInfo.FileNames == null || uploadInfo.FileNames.Length <= 0)
                {
                    return new ContentResult()
                    {
                        Content = string.Format("<script>alert(\"您还没有上传任何附件\");window.location='{0}'</script>", Request.UrlReferrer.ToString())
                    };
                }
                var campaignUploads = uploadInfo.FileNames.Select(s => new CampUpLoad()
                {
                    UpLoad = s,
                    Name = s,
                    CampaignID = campaign.ID,
                    IsDel = false,
                    Status = (int)CampUpLoadState.unfinished,
                    Type=campaign.Mortgage==4?(int)CampUpLoadType.Agent:(int)CampUpLoadType.Person
                }).ToArray();
                if (campaign.Type == (int)MortgageAttachment.House)
                {
                    curAccount.Money = curAccount.Money - decimal.Parse(System.Configuration.ConfigurationManager.AppSettings["CheckHouseMoney"]);
                }
                else
                {
                    curAccount.Money = curAccount.Money - decimal.Parse(System.Configuration.ConfigurationManager.AppSettings["CheckCarMoney"]);
                }
                campaign.Status = (int)CampaignState.LookThrough;
                if (campaign.CampUpLoad != null)
                {
                    CampUpLoad[] dcds= campaign.CampUpLoad.ToArray();
                    for (int i = dcds.Length - 1; i >= 0; i--)
                    {
                        CampUpLoad dcd = dcds[i];
                        campaign.CampUpLoad.Remove(dcd);
                        context.Delete<CampUpLoad>(dcd);
                    }
                }

                foreach (CampUpLoad cd in campaignUploads)
                    context.Add<CampUpLoad>(cd);
                context.Update(curAccount);
                context.Update(campaign);

                return RedirectToAction("index", "myborrows");
            }
        }

        public ActionResult NavToUploadifyMortgage(int borrowId)
        {
            using (var context = new Repository<P2PModelContainer>())
            {
                Account curAccount = context.GetEntityByID<Account>(CurrentUserInfo.ID);
                Campaign campaign = context.GetEntityByID<Campaign>(borrowId, new List<string>(new[] { "CampUpLoad" }));
                CampUpLoad[] campUpLoads = campaign.CampUpLoad.Where(w => !w.IsDel && w.Status == (int)CampUpLoadState.unfinished).ToArray();
                ContentResult result = null;
                if (CheckCampaign(campaign, curAccount, out result))
                {
                    if (campaign.Mortgage == 4)
                    {
                        ViewData["CampaignID"] = campaign.ID;
                        return View("uploadifyAgent", campUpLoads);
                    }
                    else
                    {
                        ViewData["CampaignID"] = campaign.ID;
                        ViewData["Mortgage"] = campaign.Mortgage;
                        return View("uploadifyMortgage", campUpLoads);
                    }
                }
                else
                {
                    return result;
                }
            }

        }
    }
}
